package com.talkingdata.hadoop.guard.util;

import com.talkingdata.hadoop.guard.bean.XmlConfig;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class LoadConfig {
    public static Logger logger= Logger.getLogger(LoadConfig.class);

    String XMLPATH = "conf/";
    String XMLCONF = XMLPATH + "configure.xml";

    public ArrayList<XmlConfig> readxml(){
        ArrayList<XmlConfig> xmlConfigList = new ArrayList<>();
        SAXReader reader = new SAXReader();
        reader.setEncoding("utf-8");
        Document document = null;
        try {
            document = reader.read(XMLCONF);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        Element root = document.getRootElement();
        List<Element> list = root.elements("cluster");
        for ( Element e : list ){
            String serviceId = e.element("serviceId").getStringValue();
            String confDir = XMLPATH  + serviceId + "/";
            Boolean kerberos = Boolean.parseBoolean(e.element("kerberos").getStringValue());
            String kerberosUser = "";
            String kerberosKeytab = "";
            if (kerberos){
                kerberosUser = e.element("kerberos_user").getStringValue();
                kerberosKeytab = e.element("kerberos_keytab").getStringValue();
            }
            String scheduler = e.element("scheduler").getStringValue();
            String version = e.element("version").getStringValue();
            XmlConfig xc = new XmlConfig(serviceId,confDir,kerberos,kerberosUser,kerberosKeytab,scheduler,version);
            xmlConfigList.add(xc);
            logger.info(xc.toString());
        }
        return xmlConfigList;
    }
}
